package com.gnerv.sylvanas.extend.rabbit.autoconfigure;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ligen
 */
@Configuration
public class ExtendRabbitConfiguration {

    private static final Map<String, ConnectionFactory> CONNECTION_FACTORY_MAP = new HashMap<>();

    public ExtendRabbitConfiguration(ExtendRabbitProperties extendRabbitProperties) {
        Map<String, RabbitProperties> multiCenter = extendRabbitProperties.getMultiCenter();
        for (Map.Entry<String, RabbitProperties> stringRabbitPropertiesEntry : multiCenter.entrySet()) {
            RabbitProperties rabbitProperties = stringRabbitPropertiesEntry.getValue();
            CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
            connectionFactory.setHost(rabbitProperties.getHost());
            connectionFactory.setPort(rabbitProperties.getPort());
            connectionFactory.setUsername(rabbitProperties.getUsername());
            connectionFactory.setPassword(rabbitProperties.getPassword());
            connectionFactory.setVirtualHost(rabbitProperties.getVirtualHost());
            // 高级配置
            if (rabbitProperties.getConnectionTimeout() != null) {
                connectionFactory.setConnectionTimeout(rabbitProperties.getConnectionTimeout().toMillisPart());
            }

            if (rabbitProperties.getRequestedHeartbeat() != null) {
                connectionFactory.setRequestedHeartBeat(Long.bitCount(rabbitProperties.getRequestedHeartbeat().getSeconds()));
            }
            // 连接池配置
            connectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CHANNEL);
            connectionFactory.setChannelCacheSize(25);
            connectionFactory.setChannelCheckoutTimeout(1000);
            CONNECTION_FACTORY_MAP.put(stringRabbitPropertiesEntry.getKey(), connectionFactory);
        }
    }

    public ConnectionFactory getConnectionFactory(String key) {
        return CONNECTION_FACTORY_MAP.get(key);
    }

    public ConnectionFactory setConnectionFactory(String key, ConnectionFactory connectionFactory) {
        return CONNECTION_FACTORY_MAP.put(key, connectionFactory);
    }

}
